#!/usr/bin/python
# coding=utf8
#
# Copyright (C) 2011 XNData contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


__author__ = "zhangchitc@gmail.com"


import urllib2, urllib
import re, json
import time, datetime
import xndata.client
import xndata.data.comment


class CommentUrlMgr:

    next_id = {}

    @staticmethod
    def album_comment_url (owner_id, album_id, cur_page):
        return "http://photo.renren.com/photo/%s/album-%s/comment?page=%d&album=%s&owner=%s" % (
                owner_id, album_id, cur_page, album_id, owner_id)

    @staticmethod
    def photo_comment_url (owner_id, photo_id, cur_page):
        return "http://photo.renren.com/photo/%s/photo-%s/comment?page=%d&photo=%s&owner=%s" % (
                owner_id, photo_id, cur_page, photo_id, owner_id)

    @staticmethod
    def status_comment_url (user_id, status_id):
        return "http://status.renren.com/feedcommentretrieve.do?doingId=%s&source=%s&owner=%s&t=3" % (
                status_id, status_id, user_id)

    @staticmethod
    def note_comment_url (author_id, note_id, cur_page):
        if cur_page == 0:
            return "http://blog.renren.com/blog/%s/%s" % (author_id, note_id)
        else:
            return "http://blog.renren.com/blog/%s/%s/comment/list/by-%s" % (
                        author_id, note_id, 
                        CommentUrlMgr.next_id[(author_id, note_id, cur_page)])
            

class CommentPageFetcher:

    @staticmethod
    def fetch_album_comment_list_page (opener, owner_id, album_id, cur_page):
        request = urllib2.Request (CommentUrlMgr.album_comment_url (
                    owner_id, album_id, cur_page))
        return opener.open (request).read ()

    @staticmethod
    def fetch_photo_comment_list_page (opener, owner_id, photo_id, cur_page):
        request = urllib2.Request (CommentUrlMgr.photo_comment_url (
                    owner_id, photo_id, cur_page))
        return opener.open (request).read ()

    @staticmethod
    def fetch_status_comment_list_page (opener, user_id, status_id):
        request = urllib2.Request (CommentUrlMgr.status_comment_url (
                    user_id, status_id))
        return opener.open (request).read ()

    @staticmethod
    def fetch_note_comment_list_page (opener, author_id, note_id, cur_page):
        request = urllib2.Request (CommentUrlMgr.note_comment_url (
                    author_id, note_id, cur_page))
        html = opener.open (request).read ()

        if cur_page == 0:
            start = html.find (r'comments:{"hasMore":')
            end = html.find ('});\n});XN.DOM.readyDo(function()')
            html = html[start + 9 : end]

        json_obj = json.loads (html)
        CommentUrlMgr.next_id [(author_id, note_id, cur_page + 1)] = \
            str (int (json_obj["comments"][0]["id"]))
        
        return html

class CommentPageParser:

    @staticmethod
    def get_total_comment (html):
        json_obj = json.loads (html)
        return json_obj["commentCount"]

    @staticmethod
    def get_comment_list (html, cur_page):
        json_obj = json.loads (html)
        json_comment_list = json_obj["comments"]
        comment_list = xndata.data.comment.CommentList (cur_page = cur_page)

        for json_comment in json_comment_list:
            author_id = str (json_comment["author"])
            author_name = str (json_comment["name"].encode ("utf-8"))
            comment_id = str (int (json_comment["id"]))
            body = str (json_comment["body"].encode ("utf-8"))
            pub_time_struct = time.strptime (str (json_comment["time"]), "%Y-%m-%d %H:%M")
            pub_time = datetime.datetime (*pub_time_struct[0:5])
            comment = xndata.data.comment.Comment (
                        author_id = author_id, author_name = author_name,
                        comment_id = comment_id, body = body,
                        pub_time = pub_time)
            comment_list.addComment (comment)
        comment_list.clist.reverse ()
        return comment_list

    @staticmethod
    def get_status_comment_list (html):
        json_obj = json.loads (html)
        json_comment_list = json_obj["replyList"]
        comment_list = xndata.data.comment.CommentList (cur_page = 0)

        for json_comment in json_comment_list:
            author_id = str (json_comment["ubid"])
            author_name = str (json_comment["ubname"].encode ("utf-8"))
            comment_id = str (int (json_comment["id"]))
            body = str (json_comment["replyContent"].encode ("utf-8"))
            pub_time_struct = time.strptime (str (json_comment["replyTime"]), "%Y-%m-%d %H:%M")
            pub_time = datetime.datetime (*pub_time_struct[0:5])
            comment = xndata.data.comment.Comment (
                        author_id = author_id, author_name = author_name,
                        comment_id = comment_id, body = body,
                        pub_time = pub_time)
            comment_list.addComment (comment)
        return comment_list


if __name__ == "__main__":
    client = xndata.client.XNClient ("zhangchitc@gmail.com", "aaaaaaaa")
    #html = CommentPageFetcher.fetch_album_comment_list_page (
    #        client.opener, "242124580", "420591415", 0)
    #html = CommentPageFetcher.fetch_photo_comment_list_page (
    #        client.opener, "242124580", "4382049543", 0)
    #CommentPageParser.get_comment_list (html, 0)
    #html = CommentPageFetcher.fetch_status_comment_list_page (
    #        client.opener, "249044591", "1903259986", client.request_token)
    #print html
    #CommentPageParser.get_status_comment_list (html)
    html = CommentPageFetcher.fetch_note_comment_list_page (client.opener, "242124580", "719803155", 0)
